<template>
  <el-card class="box-card">
    <el-button type="primary" :icon="Plus" @click="showSaveDialog"
      >添加</el-button
    >

    <!-- 
        el-table 
        data 要渲染的数据
        border 带边框

        el-table-column 列
        type ='index' 渲染的序列号
        align="center"  对齐的方式
        prop 要渲染数据中哪个属性的值

        如果只要渲染纯数据，直接prop 
        如果只要渲染的一些其他结构（组件），用默认插槽
       -->
    <el-table
      :data="trademarkList"
      border
      style="width: 100%"
      class="el-table-content"
    >
      <el-table-column type="index" label="系号" align="center" width="80" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <template #default="{ row }">
          <img :src="row.logoUrl" :alt="row.tmName" class="TrademarkImg"
        /></template>
      </el-table-column>
      <el-table-column label="操作">
        <!-- #default="scope" -->
        <template #default="{ row }">
          <el-tooltip content="修改品牌" placement="top" effect="light">
            <el-button
              content="修改品牌"
              size="small"
              type="warning"
              :icon="Edit"
              @click="showUpdateDialog(row)"
            />
          </el-tooltip>
          <el-tooltip content="删除品牌" placement="top" effect="light">
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click="delTrdemark(row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 
      v-model: currentPage 当前页码
      v-model：page-size 每页条数
      page-sizes 可以选择每条页数的值
      layout 放入需要使用的组件
      total 总数
      @current-change  当currentPage发生变化时触发
      @size-change     当page-size发生变化时触发
     -->
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout=" prev, pager, next, jumper,total, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>

  <el-dialog
    v-model="dialogVisible"
    :title="(trademarkFormData.id ? '修改' : '添加') + '品牌'"
  >
    <!-- <span>This is a message</span> -->
    <el-form
      ref="trademarkFormRef"
      :model="trademarkFormData"
      :rules="trademarkFormRules"
      label-width="100px"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input
          type="text"
          class="trademark-input"
          v-model="trademarkFormData.tmName"
        />
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/app-dev/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkFormData.logoUrl"
            :src="trademarkFormData.logoUrl"
            class="trademark"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
export default {
  name: "XTrademark",
};
</script>

<script lang="ts" setup>
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps, FormRules, FormInstance } from "element-plus";
import { ref, onMounted, reactive } from "vue";
import {
  getTrademarkListApi,
  saveTrademarkApi,
  getUpdateTrademarkApi,
  gitDelTrademarkApi,
} from "@/api/product/trademark";
import type {
  TrademarkList,
  TrademarkItem,
} from "@/api/product/modles/trdemarkModel";

// 响应式数据 当前页
const currentPage = ref(2);
// 响应式数据 当前条数
const pageSize = ref(3);
// 响应式数据 当前总条数
const total = ref(0);

const trademarkList = ref<TrademarkList>([]);

// 挂载时获取数据
onMounted(async () => {
  getTrademarkList();
});

//  封装请求函数
const getTrademarkList = async () => {
  const result = await getTrademarkListApi(currentPage.value, pageSize.value);
  trademarkList.value = result.records;
  total.value = result.total;
};
// 表单数据

//  条数改变需要重新发送请求
const handleSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize;
  getTrademarkList();
};
//  当前页改变时需要重新发送请求
const handleCurrentChange = (newCurrentPage: number) => {
  currentPage.value = newCurrentPage;
  getTrademarkList();
};

// 对话框
const dialogVisible = ref(false);

const trademarkFormRef = ref<FormInstance>();
// 申明响应式数据
const trademarkFormData = reactive({
  // 定义表单名称：要和发送请求一致，要和数据源一致
  id: 0,
  tmName: "",
  logoUrl: "",
});

// 表单校验的规则: 规则名称，必须和表单数据名称一致
const trademarkFormRules = reactive<FormRules>({
  tmName: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
  logoUrl: [{ required: true, message: "请上传品牌logo", trigger: "blur" }],
});

const submitForm = () => {
    //表单Dom元素 。validate被效验会触发   valid效验结果
  trademarkFormRef.value?.validate(async (valid) => {
    const { id, tmName, logoUrl } = trademarkFormData;
    if (valid) {
      // const { tmName, logoUrl } = trademarkFormData;

      if (id) {
        await getUpdateTrademarkApi({ tmName, logoUrl, id });
        ElMessage.success("修改品牌成功");
      } else {
        await saveTrademarkApi(tmName, logoUrl);
        ElMessage.success("添加品牌成功");
      }

      // resetFields 表单清空数据的方法
      trademarkFormRef.value?.resetFields();

      // 并且隐藏对话框
      dialogVisible.value = false;
      // 重新调用发送请求，刷新数据
      getTrademarkList();
    }
  });
};

// 图片上传成功触发的函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  trademarkFormData.logoUrl = response.data;
};
// 图片上传时触发的函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const typeFile = ["image/jpeg", "image/jpg", "image/png"];
  if (!typeFile.includes(rawFile.type)) {
    ElMessage.error("上传图片格式必须jpg或者png!");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("上传图片大小不能超过200kb");
    return false;
  }
  return true; //继续上传图片
};
// 点击添加
const showSaveDialog = () => {
  trademarkFormData.id = 0;
  trademarkFormData.tmName = "";
  trademarkFormData.logoUrl = "";
  dialogVisible.value = true;
  trademarkFormRef.value?.clearValidate();
};

// 点击修改
const showUpdateDialog = (row: TrademarkItem) => {
  console.log(row);

  trademarkFormData.id = row.id;
  trademarkFormData.tmName = row.tmName;
  trademarkFormData.logoUrl = row.logoUrl;
  dialogVisible.value = true;
  trademarkFormRef.value?.clearValidate();
};

// 点击删除
const delTrdemark = (row: TrademarkItem) => {
  ElMessageBox.confirm(`确定删除 ${row.tmName} 吗？`, "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await gitDelTrademarkApi(row.id);
    ElMessage({
      type: "success",
      message: "该尚品已删除",
    });
    getTrademarkList();
  });
};
</script>

<style scoped>
.TrademarkImg {
  width: 150px;
  height: 100px;
}
.trademark-input {
  width: 300px;
}
.el-table-content {
  margin: 20px 0;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style>
.trademark-table {
  margin: 20px 0;
}
</style>